package com.tianze.library.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.tianze.library.R;
import com.tianze.library.listener.SingleClickListener;
import com.tianze.library.view.SimpleDialog;

import butterknife.ButterKnife;

/**
 * Created by kingtami.
 */
public class BaseWebViewFragment extends BaseFragment {

    protected WebView mWebView;

    private static final int TIME_OUT = 30 * 1000;

    private static Handler handler = new Handler();

    private Runnable closeRunnable = new Runnable() {
        @Override
        public void run() {
            hideWaitingDialog();
            mWebView.stopLoading();
            showCustomConfirmDialog(
                    "页面加载超时,是否重试?", "重试", "取消", new SimpleDialog.OnSimpleClickListener() {
                        @Override
                        public void onClick(SimpleDialog simpleDialog) {
                            mWebView.reload();
                            simpleDialog.dismiss();
                        }
                    }, null);
        }
    };

    @Override
    public boolean onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tiza_fragment_webview;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        mWebView = ButterKnife.findById(rootView, R.id.webView);
        setRightActionResource(R.drawable.icon_right_close);
        hideRightAction();
        setRightActionListener(new SingleClickListener() {
            @Override
            public void onSingleClick(View view) {
                mWebView.stopLoading();
                handler.removeCallbacks(closeRunnable);
                finish();
            }
        });
        setUpViewComponent();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        handler.removeCallbacks(closeRunnable);
    }

    private void setUpViewComponent() {
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setDisplayZoomControls(false);
        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setDefaultTextEncodingName("UTF-8");
        mWebSettings.setSupportMultipleWindows(true);
        mWebSettings.setLoadsImagesAutomatically(true);

        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 50);//设置缓冲大小，8M
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        String appCacheDir = getActivity().getApplicationContext()
                                          .getDir("cache", Context.MODE_PRIVATE).getPath();
        mWebSettings.setAppCachePath(appCacheDir);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        setWebViewListener();
    }

    private void setWebViewListener() {
        WebViewClient webClient = new CustomWebViewClient();
        mWebView.setWebViewClient(webClient);
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }

            //扩充缓存的容量
            @Override
            public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(spaceNeeded * 2);
            }
        });

        mWebView.setOnLongClickListener(new View.OnLongClickListener()

                                        {
                                            @Override
                                            public boolean onLongClick(View arg0) {
                                                return true;
                                            }
                                        }

        );
    }

    private class CustomWebViewClient extends WebViewClient {

        public CustomWebViewClient() {
            super();
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onLoadResource(WebView view, String url) {

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            try {
                showRightImageAction();
                handler.removeCallbacks(closeRunnable);
            } catch (Exception e) {

            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            try {
                handler.postDelayed(closeRunnable, TIME_OUT);
            } catch (Exception e) {

            }
        }
    }

}
